package com.feri.rbacsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feri.rbacsys.bo.PermissionAddBo;
import com.feri.rbacsys.bo.PermissionBo;
import com.feri.rbacsys.dao.PermissionDao;
import com.feri.rbacsys.dao.RolePermissionDao;
import com.feri.rbacsys.entity.Permission;
import com.feri.rbacsys.entity.RolePermission;
import com.feri.rbacsys.service.intf.PermissionService;
import com.feri.rbacsys.util.AuthUtil;
import com.feri.rbacsys.util.MenuUtil;
import com.feri.rbacsys.vo.R;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 18.权限表(SysPermission)表服务实现类
 *
 * @author makejava
 * @since 2023-03-26 10:40:28
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionDao dao;
    @Resource
    private RolePermissionDao rolePermissionDao;


    /**
     * 新增权限
     * @param bo
     * @return
     */
    @Override
    public R add(PermissionBo bo) {
        //1.验证
        if(bo!=null){
            Permission permission=new Permission();
            BeanUtils.copyProperties(bo,permission);
            if(dao.insert(permission)>0){
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R queryAll() {
       //1.查询
        QueryWrapper<Permission> wrapper=new QueryWrapper<>();
        wrapper.orderByAsc("type");
        wrapper.orderByAsc("level");
        List<Permission> list=dao.selectList(wrapper);
        return R.ok(MenuUtil.ceateMenu(list));
    }

    /**
     * 根据uid获取当前登录用户的菜单树
     * @return
     */
    @Override
    public R queryMenuByUid() {
        List<Permission> list=dao.selectMenuByUid(AuthUtil.getUid());
        return R.ok(MenuUtil.parseMenu(MenuUtil.ceateMenu(list)));
    }

    /**
     * 根据uid获取当前登录用户的权限列表
     * @return
     */
    @Override
    public R queryPermByUid() {
        return R.ok(dao.selectPermByUid(AuthUtil.getUid()));
    }

    /**
     * 修改角色的权限列表
     * @param bo
     * @return
     */
    @Override
    public R updateByUid(PermissionAddBo bo) {
        //1.先删除原来的
        rolePermissionDao.deleteByRid(bo.getRid());
        //2.再新增本次的
        List<RolePermission> list=new ArrayList<>(bo.getPids().size());
        bo.getPids().forEach(pid->{
            list.add(new RolePermission(bo.getRid(),pid));
        });
        rolePermissionDao.insertBatch(list);
        return R.ok();
    }

}

